// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.asm;

import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * Removes in-place jump instructions.
 * 
 * TODO(micapolos): This is not working yet.
 * 
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class InplaceJumpRemover extends InsnAdviceAdapter {

  private Runnable jumpInsn = null;
  
  public InplaceJumpRemover(MethodVisitor out) {
    super(out);
  }

  @Override
  public void visitJumpInsn(final int opcode, final Label label) {
    if (opcode != Opcodes.JSR) {
      releaseJumpInsn();
      
      jumpInsn = new Runnable() {
        public void run() {
          mv.visitJumpInsn(opcode, label);
        }
      };
    } else {
      super.visitJumpInsn(opcode, label);
    }
  }

  @Override
  protected void beforeInsn() {
    releaseJumpInsn();
  }
  
  /**
   * Releases suspended jump instruction.
   */
  private void releaseJumpInsn() {
    if (jumpInsn != null) {
      jumpInsn.run();
    }
    jumpInsn = null;
  }
}
